import format from "date-fns/format";
import _ from "lodash";
import { Notification } from "element-ui";

export const switchScreen = el => {
  if (isFullscreen()) {
    exitScreen();
    return false;
  } else {
    setFullScreen(el);
    return true;
  }
};

export const setFullScreen = el => {
  var rfs =
    el.requestFullScreen ||
    el.webkitRequestFullScreen ||
    el.mozRequestFullScreen ||
    el.msRequestFullscreen;
  if (typeof rfs != "undefined" && rfs) {
    rfs.call(el);
  }
  return;
};

export const exitScreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitCancelFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  }
};

export const isFullscreen = () => {
  return (
    document.fullscreenElement ||
    document.msFullscreenElement ||
    document.mozFullScreenElement ||
    document.webkitFullscreenElement ||
    false
  );
};

export const checknumber = String => {
  return /^-?\d+\.?(\d+)?$/.test(String);
};

export const formatTime = time => {
  let sec_num = parseInt(time, 10); // don't forget the second param
  let hours = Math.floor(sec_num / 3600);
  let minutes = Math.floor((sec_num - hours * 3600) / 60);
  let seconds = sec_num - hours * 3600 - minutes * 60;

  if (hours == 0) {
    return `${minutes < 10 ? "0" + minutes : minutes}:${
      seconds < 10 ? "0" + seconds : seconds
    }`;
  } else {
    return `${hours < 10 ? "0" + hours : hours}:${
      minutes < 10 ? "0" + minutes : minutes
    }:${seconds < 10 ? "0" + seconds : seconds}`;
  }
};

export const randomId = () => {
  var Num = "";
  for (var i = 0; i < 6; i++) {
    Num += Math.floor(Math.random() * 10);
  }
  return Num;
};

export const saveJSON = (data, filename) => {
  if (!data) {
    alert("保存的数据为空");
    return;
  }
  if (!filename) filename = "json.json";
  if (typeof data === "object") {
    data = JSON.stringify(data, undefined, 4);
  }
  var blob = new Blob([data], {
      type: "text/json"
    }),
    e = document.createEvent("MouseEvents"),
    a = document.createElement("a");
  a.download = filename;
  a.href = window.URL.createObjectURL(blob);
  a.dataset.downloadurl = ["text/json", a.download, a.href].join(":");
  e.initMouseEvent(
    "click",
    true,
    false,
    window,
    0,
    0,
    0,
    0,
    0,
    false,
    false,
    false,
    false,
    0,
    null
  );
  a.dispatchEvent(e);
};

export const rightClickStop = e => {
  if (e.which === 3) {
    e.preventDefault();
  }
};

export const eventFrom = (event, tag) => {
  let target = document.querySelector(tag);
  if (tag) {
    for (let i of event.path) {
      if (i == target) {
        return true;
      }
    }
  }
  return false;
};

export const getLabel = (value, labels, unkn) => {
  for (let item of labels) {
    if (item.value == value) {
      return item.label;
    }
  }
  if (unkn) {
    return unkn;
  }
  return "-";
};

export const calSize = size => {
  size = parseFloat(size);
  if (size < 10e3) {
    return `${size.toFixed(2)} B`;
  } else if (size < 10e6) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else if (size < 10e9) {
    return `${(size / 1024 / 1024).toFixed(2)} MB`;
  } else {
    return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
  }
};

export const inArray = (row, list, key) => {
  return list.find(item => {
    try {
      return item[key] == row[key];
    } catch (error) {
      return false;
    }
  });
};

export const sleep = sec => {
  return new Promise(res => {
    setTimeout(res, sec);
  }, sec);
};

export const combineNoneVoid = (a, b) => {
  a = _.cloneDeep(a);
  b = _.cloneDeep(b);
  if (!a) {
    return b || {};
  }
  if (!b) {
    return a || {};
  }
  for (let key in a) {
    if (!a[key]) {
      continue;
    }
    if (b[key]) {
      if (a[key].constructor == Object && b[key].constructor == Object) {
        a[key] = this.combineNoneVoid(a[key], b[key]);
      } else {
        a[key] = b[key];
      }
    }
  }
  for (let key in b) {
    if (!a[key]) {
      a[key] = b[key];
    }
  }
  return a;
};

export const timeConverter = (time, format) => {
  let base = time / 1000;
  let hr = parseInt(base / 3600);
  let min = parseInt((base - hr * 3600) / 60);
  let sec = parseInt(base - hr * 3600 - min * 60);
  hr < 10 ? (hr = "0" + hr) : false;
  min < 10 ? (min = "0" + min) : false;
  sec < 10 ? (sec = "0" + sec) : false;
  format = format.replace("hh", hr);
  format = format.replace("mm", min);
  format = format.replace("ss", sec);
  return format;
};
export const timeReConverter = time => {
  time = time.split(":");
  return (
    (parseInt(time[0]) * 3600 + parseInt(time[1]) * 60 + parseInt(time[2])) *
    1000
  );
};
export const numbrize = obj => {
  let output = {};
  for (let key in obj) {
    output[key] = parseFloat(obj[key]);
  }
  return output;
};

export const wgsToGcj = input => {
  let GCJ_A = 6378245,
    GCJ_EE = 0.00669342162296594323,
    x = input.lng - 105,
    y = input.lat - 35;
  let dLat =
      -100 +
      2 * x +
      3 * y +
      0.2 * y * y +
      0.1 * x * y +
      0.2 * Math.sqrt(Math.abs(x)) +
      ((2 * Math.sin(x * 6 * Math.PI) +
        2 * Math.sin(x * 2 * Math.PI) +
        2 * Math.sin(y * Math.PI) +
        4 * Math.sin((y / 3) * Math.PI) +
        16 * Math.sin((y / 12) * Math.PI) +
        32 * Math.sin((y / 30) * Math.PI)) *
        20) /
        3,
    dLng =
      300 +
      x +
      2 * y +
      0.1 * x * x +
      0.1 * x * y +
      0.1 * Math.sqrt(Math.abs(x)) +
      ((2 * Math.sin(x * 6 * Math.PI) +
        2 * Math.sin(x * 2 * Math.PI) +
        2 * Math.sin(x * Math.PI) +
        4 * Math.sin((x / 3) * Math.PI) +
        15 * Math.sin((x / 12) * Math.PI) +
        30 * Math.sin((x / 30) * Math.PI)) *
        20) /
        3,
    radLat = (input.lat * Math.PI) / 180;
  let magic = 1 - GCJ_EE * Math.pow(Math.sin(radLat), 2);
  let lat_deg_arclen =
      ((Math.PI / 180) * (GCJ_A * (1 - GCJ_EE))) / Math.pow(magic, 1.5),
    lng_deg_arclen =
      (Math.PI / 180) * ((GCJ_A * Math.cos(radLat)) / Math.sqrt(magic));
  return {
    lat: input.lat + dLat / lat_deg_arclen,
    lng: input.lng + dLng / lng_deg_arclen
  };
};

export const gcjToWgs = input => {
  let prc = 1e-5,
    i = 0,
    that = this;

  function gTw(input) {
    return lnglatDiff(input, lnglatDiff(that.wgsToGcj(input), input));
  }

  function lnglatDiff(a, b) {
    return {
      lng: a.lng - b.lng,
      lat: a.lat - b.lat
    };
  }
  let curr = gTw(input);
  let diff = {
    lat: Infinity,
    lng: Infinity
  };
  while (Math.max(Math.abs(diff.lat), Math.abs(diff.lng)) > prc && i++ < 10) {
    diff = lnglatDiff(that.wgsToGcj(curr), input);
    curr = lnglatDiff(curr, diff);
  }

  return curr;
};
export const getDelta = (before, after) => {
  let minus = after - before;
  if (minus >= 0) {
    if (minus <= 180) {
      return minus;
    }
    return after - 360 - before;
  } else {
    if (minus >= -180) {
      return minus;
    }
    return 360 + after - before;
  }
};
export const getSum = (a, b) => {
  let sum = a + b;
  if (sum < 0) {
    return 360 + sum;
  }
  return sum % 360;
};

export const createElementFromString = str => {
  const div = document.createElement("div");
  div.innerHTML = str.trim();
  return div.firstElementChild;
};
